package net.sx.minemodule.mvp.activities;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.classify.model.Constant;
import com.kedll.library.base.MyBaseFragmentActivity;
import com.kedll.library.mvp.BasePresenter;
import com.kedll.library.util.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import net.sx.minemodule.R;
import net.sx.minemodule.adapter.GridImageAdapter;
import net.sx.minemodule.databinding.MineActivityFeedbackBinding;
import net.sx.minemodule.mvp.presenters.MineFeedbackUploadPresenter;
import net.sx.minemodule.widget.FullyGridLayoutManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 意见反馈
 */
//@RuntimePermissions
@Route(path = ARouterPath.PATH_MINE_FEEDBACK)
public class FeedbackActivity extends MyBaseFragmentActivity<MineActivityFeedbackBinding, MineFeedbackUploadPresenter> implements CompoundButton.OnCheckedChangeListener {
    private PopupWindow pop;
    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNum = 3;
    private RecyclerView mRecyclerView; //展示图片的控件
    private StringBuilder sb;   //把选择的type拼接起来

    private CheckBox productPos, viewPos, operatingPos, propose, errorPos, otherPos;    //依次是商品问题，界面问题，操作问题，优化建议，卡顿报错，其他问题
    private List<String> checkBoxString ;   //checkbox 的集合
    private EditText infoEdit;  //输入反馈内容控件
    private Button btnSubmit;   //提交按钮

    private OSSClient ossClient;
    private String filePath;


    @Override
    protected MineFeedbackUploadPresenter getPresenter() {
        return new MineFeedbackUploadPresenter(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.mine_activity_feedback;
    }

    @Override
    protected void initToolBar(Bundle savedInstanceState) {
        super.initToolBar(savedInstanceState);
        setTitle("意见反馈");
    }

    @Override
    protected void initEvent() {
        //TODO
        mRecyclerView = mBinding.feedbackUpload.recycler;
        btnSubmit = mBinding.btnSubmit;

        checkBoxString = new ArrayList<>(); //装选择的类型

        initFeedbackType();
        initWidget();
//        FeedbackActivityPermissionsDispatcher.showPopWithPermissionCheck(this);

        infoEdit = mBinding.feedbackInfo.findViewById(R.id.info_edit);

        btnSubmit.setOnClickListener(v -> {
            Log.d(TAG, "onClick: sb  == " + sb + "  info == " + infoEdit.getText().toString());
//            uoloadImg(Constant.BUCKET_NAME, filePath);
//            mPresenter.submitData(sb, infoEdit.getText().toString());
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

    }

    private void initOSS() {
        OSSCredentialProvider credentialProvider;
        credentialProvider = new OSSAuthCredentialsProvider(Constant.STS_SERVER_URL);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        ossClient = new OSSClient(getApplicationContext(), Constant.OSS_ENDPOINT, credentialProvider, conf);
    }

    /*private void uoloadImg(String objectName, String filePath) {
        if (objectName.equals("")) {
            Log.w("AsyncPutImage", "ObjectNull");
            return;
        }
        File file = new File(filePath);
        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            return;
        }
        PutObjectRequest put = new PutObjectRequest(Constant.BUCKET_NAME, objectName, filePath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);
//                mDisplayer.updateProgress(progress);
//                mDisplayer.displayInfo("上传进度: " + String.valueOf(progress) + "%");
                Log.d(TAG, "onProgress   上传进度: " + String.valueOf(progress) + "%");
            }
        });
    }*/

    /**
     * 初始化反馈类型CheckBox控件
     */
    private void initFeedbackType() {
        productPos = mBinding.feedbackType.findViewById(R.id.product_position);
        viewPos = mBinding.feedbackType.findViewById(R.id.view_position);
        operatingPos = mBinding.feedbackType.findViewById(R.id.operating_position);
        propose= mBinding.feedbackType.findViewById(R.id.propose);
        errorPos = mBinding.feedbackType.findViewById(R.id.error_position);
        otherPos = mBinding.feedbackType.findViewById(R.id.other_position);

        productPos.setOnCheckedChangeListener(this);
        viewPos.setOnCheckedChangeListener(this);
        operatingPos.setOnCheckedChangeListener(this);
        propose.setOnCheckedChangeListener(this);
        errorPos.setOnCheckedChangeListener(this);
        otherPos.setOnCheckedChangeListener(this);
    }

    /*@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        FeedbackActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }*/

    /**
     * 初始化从图库、相机中获取图片展示控件
     */
    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener((position, v) -> {
            if (selectList.size() > 0) {
                LocalMedia media = selectList.get(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                        PictureSelector.create(FeedbackActivity.this).externalPicturePreview(position, selectList);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(FeedbackActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(FeedbackActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        });
    }

//    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})

    /**
     * 从图库、相机中获取图片弹框
     */
    public void showPop() {
        View bottomView = View.inflate(this, R.layout.le_select_layout, null);
        TextView mAlbum = bottomView.findViewById(R.id.galleryBtn);
        TextView mCamera = bottomView.findViewById(R.id.photoBtn);
        TextView mCancel = bottomView.findViewById(R.id.cancelBtn);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = getWindow().getAttributes();
            lp1.alpha = 1f;
            getWindow().setAttributes(lp1);
        });
        pop.setAnimationStyle(R.style.mine_main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = view -> {
            int i = view.getId();
            if (i == R.id.galleryBtn) {//相册
                PictureSelector.create(FeedbackActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(maxSelectNum)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);

            } else if (i == R.id.photoBtn) {//拍照
                PictureSelector.create(FeedbackActivity.this)
                        .openCamera(PictureMimeType.ofImage())
                        .forResult(PictureConfig.CHOOSE_REQUEST);

            } else if (i == R.id.cancelBtn) {//取消
                //closePopupWindow();
            }
            closePopupWindow();
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    /**
     * 关闭下拉弹框
     */
    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    /**
     * 添加图片时的点击事件
     */
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            showPop();
        }
    };

    /**
     * 选择图片回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    images = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (int i = 0; i < images.size(); i++) {
                        LocalMedia media = images.get(i);
                        Log.d(TAG, "onActivityResult: media.getPath() === " + media.getPath());
                        filePath = media.getPath();
                    }
                    Log.d(TAG, "onActivityResult: ");
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 反馈类型获取回调
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            checkBoxString.add(buttonView.getText().toString());
        } else {
            String s = buttonView.getText().toString();
            checkBoxString.remove(s);
        }
        String s = "";
        sb = new StringBuilder();
        for (int i = 0; i < checkBoxString.size(); i++) {
             s = checkBoxString.get(i);
            sb.append(s);
        }
        Log.d(TAG, "onCheckedChanged: sb == " + sb);
    }
}
